
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>_thread --- 底层多线程 API &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="_dummy_thread --- _thread 的替代模块" href="_dummy_thread.html" />
    <link rel="prev" title="queue --- 一个同步的队列类" href="queue.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/_thread.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="_dummy_thread.html" title="_dummy_thread --- _thread 的替代模块"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="queue.html" title="queue --- 一个同步的队列类"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concurrency.html" accesskey="U">并发执行</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-_thread">
<span id="thread-low-level-threading-api"></span><h1><a class="reference internal" href="#module-_thread" title="_thread: Low-level threading API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code></a> --- 底层多线程 API<a class="headerlink" href="#module-_thread" title="永久链接至标题">¶</a></h1>
<hr class="docutils" id="index-0" />
<p>该模块提供了操作多个线程（也被称为 <em class="dfn">轻量级进程</em> 或 <em class="dfn">任务</em>）的底层原语 —— 多个控制线程共享全局数据空间。为了处理同步问题，也提供了简单的锁机制（也称为 <em class="dfn">互斥锁</em> 或 <em class="dfn">二进制信号</em>）。<a class="reference internal" href="threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> 模块基于该模块提供了更易用的高级多线程 API。</p>
<div class="versionchanged" id="index-1">
<p><span class="versionmodified changed">在 3.7 版更改: </span>这个模块曾经为可选项，但现在总是可用。</p>
</div>
<p>这个模块定义了以下常量和函数：</p>
<dl class="exception">
<dt id="_thread.error">
<em class="property">exception </em><code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">error</code><a class="headerlink" href="#_thread.error" title="永久链接至目标">¶</a></dt>
<dd><p>发生线程相关错误时抛出。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.3 版更改: </span>现在是内建异常 <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> 的别名。</p>
</div>
</dd></dl>

<dl class="data">
<dt id="_thread.LockType">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">LockType</code><a class="headerlink" href="#_thread.LockType" title="永久链接至目标">¶</a></dt>
<dd><p>锁对象的类型。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.start_new_thread">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">start_new_thread</code><span class="sig-paren">(</span><em class="sig-param">function</em>, <em class="sig-param">args</em><span class="optional">[</span>, <em class="sig-param">kwargs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.start_new_thread" title="永久链接至目标">¶</a></dt>
<dd><p>启动一个线程，并返回其标识符。线程会用 <em>args</em> 作为参数（必须是元组）执行 <em>function</em> 函数。可选的 <em>kwargs</em> 参数使用字典来指定有名参数。当函数返回时，线程会静默退出，当函数由于未处理的异常而中止时，会打印一条堆栈追踪信息，然后该线程会退出（但其他线程还是会继续运行）。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.interrupt_main">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">interrupt_main</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.interrupt_main" title="永久链接至目标">¶</a></dt>
<dd><p>模拟一个 <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> 信号到达主线程的效果。 线程可以使用这个函数来中断主线程。</p>
<p>如果 Python 没有处理 <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> (将它设为 <a class="reference internal" href="signal.html#signal.SIG_DFL" title="signal.SIG_DFL"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.SIG_DFL</span></code></a> 或 <a class="reference internal" href="signal.html#signal.SIG_IGN" title="signal.SIG_IGN"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.SIG_IGN</span></code></a>)，此函数将不做任何事。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.exit">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">exit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.exit" title="永久链接至目标">¶</a></dt>
<dd><p>抛出 <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> 异常。如果没有捕获的话，这个异常会使线程退出。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.allocate_lock">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">allocate_lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.allocate_lock" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的锁对象。锁中的方法在后面描述。初始情况下锁处于解锁状态。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.get_ident">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">get_ident</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.get_ident" title="永久链接至目标">¶</a></dt>
<dd><p>返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义，主要是用作 magic cookie，比如作为含有线程相关数据的字典的索引。线程标识符可能会在线程退出，新线程创建时被复用。</p>
</dd></dl>

<dl class="function">
<dt id="_thread.stack_size">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">stack_size</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.stack_size" title="永久链接至目标">¶</a></dt>
<dd><p>返回创建线程时使用的堆栈大小。可选参数 <em>size</em> 指定之后新建的线程的堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是32,768(32KiB)的一个正整数。如果 <em>size</em> 没有指定，默认是0。如果不支持改变线程堆栈大小，会抛出 <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> 错误。如果指定的堆栈大小不合法，会抛出 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> 错误并且不会修改堆栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是使用4096的倍数作为堆栈大小）。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">适用于</span></a>: Windows，具有 POSIX 线程的系统。</p>
</dd></dl>

<dl class="data">
<dt id="_thread.TIMEOUT_MAX">
<code class="sig-prename descclassname">_thread.</code><code class="sig-name descname">TIMEOUT_MAX</code><a class="headerlink" href="#_thread.TIMEOUT_MAX" title="永久链接至目标">¶</a></dt>
<dd><p><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code> 方法中 <em>timeout</em> 参数允许的最大值。传入超过这个值的 timeout 会抛出 <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> 异常。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<p>锁对象有以下方法：</p>
<dl class="method">
<dt id="_thread.lock.acquire">
<code class="sig-prename descclassname">lock.</code><code class="sig-name descname">acquire</code><span class="sig-paren">(</span><em class="sig-param">waitflag=1</em>, <em class="sig-param">timeout=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#_thread.lock.acquire" title="永久链接至目标">¶</a></dt>
<dd><p>没有任何可选参数时，该方法无条件申请获得锁，有必要的话会等待其他线程释放锁（同时只有一个线程能获得锁 —— 这正是锁存在的原因）。</p>
<p>如果传入了整型参数 <em>waitflag</em>，具体的行为取决于传入的值：如果是 0 的话，只会在能够立刻获取到锁时才获取，不会等待，如果是非零的话，会像之前提到的一样，无条件获取锁。</p>
<p>如果传入正浮点数参数 <em>timeout</em>，相当于指定了返回之前等待得最大秒数。如果传入负的 <em>timeout</em>，相当于无限期等待。如果 <em>waitflag</em> 是 0 的话，不能指定 <em>timeout</em>。</p>
<p>如果成功获取到所会返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>新的 <em>timeout</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.2 版更改: </span>现在获取锁的操作可以被 POSIX 信号中断。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="_thread.lock.release">
<code class="sig-prename descclassname">lock.</code><code class="sig-name descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.lock.release" title="永久链接至目标">¶</a></dt>
<dd><p>释放锁。锁必须已经被获取过，但不一定是同一个线程获取的。</p>
</dd></dl>

<dl class="method">
<dt id="_thread.lock.locked">
<code class="sig-prename descclassname">lock.</code><code class="sig-name descname">locked</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_thread.lock.locked" title="永久链接至目标">¶</a></dt>
<dd><p>返回锁的状态：如果已被某个线程获取，返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<p>除了这些方法之外，锁对象也可以通过 <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> 语句使用，例如：</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">_thread</span>

<span class="n">a_lock</span> <span class="o">=</span> <span class="n">_thread</span><span class="o">.</span><span class="n">allocate_lock</span><span class="p">()</span>

<span class="k">with</span> <span class="n">a_lock</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;a_lock is locked while this executes&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><strong>注意事项：</strong></p>
<blockquote>
<div></div></blockquote>
<ul class="simple" id="index-2">
<li><p>线程与中断奇怪地交互：<a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> 异常可能会被任意一个线程捕获。（如果 <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> 模块可用的话，中断总是会进入主线程。）</p></li>
<li><p>调用 <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> 或是抛出 <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> 异常等效于调用 <a class="reference internal" href="#_thread.exit" title="_thread.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">_thread.exit()</span></code></a>。</p></li>
<li><p>不可能中断锁的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> 方法 —— <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> 一场会在锁获取到之后发生。</p></li>
<li><p>当主线程退出时，由系统决定其他线程是否存活。在大多数系统中，这些线程会直接被杀掉，不会执行 <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> ... <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> 语句，也不会执行对象析构函数。</p></li>
<li><p>当主线程退出时，不会进行正常的清理工作（除非使用了 <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> ... <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> 语句），标准 I/O 文件也不会刷新。</p></li>
</ul>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>上一个主题</h4>
  <p class="topless"><a href="queue.html"
                        title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> --- 一个同步的队列类</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="_dummy_thread.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_dummy_thread</span></code> --- <code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> 的替代模块</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/_thread.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="_dummy_thread.html" title="_dummy_thread --- _thread 的替代模块"
             >下一页</a> |</li>
        <li class="right" >
          <a href="queue.html" title="queue --- 一个同步的队列类"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concurrency.html" >并发执行</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>